package netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @ClassName MyServerHandler
 * @Description TODO
 * @Author director吴
 * @Date 2022/4/21 13:22
 * @Version 1.0
 **/
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol buf) throws Exception {

        byte[] count = buf.getCount();
        int lenth = buf.getLenth();


        String mess = new String(count, Charset.forName("utf-8"));
        System.out.println("服务器接收到的长度："+lenth);
        System.out.println("服务器接收到的内容："+mess);

        System.out.println("服务器接收到的内容："+(++this.count));

        String msg = "收到通知！返回的已读加密Key值：["+UUID.randomUUID().toString()+"]";
        MessageProtocol messageProtocol = new MessageProtocol();
        byte[] msgBytes = msg.getBytes(Charset.forName("utf-8"));



        messageProtocol.setLenth(msgBytes.length);
        messageProtocol.setCount(msgBytes);

        ctx.writeAndFlush(messageProtocol);



    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
